import 'dart:async';

import 'package:film/controller/auth_controller.dart';
import 'package:film/service/api_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  AuthController authController = Get.put(AuthController());
  final DioService _apiService = DioService();
  // 是否为登录模式，true为登录，false为注册
  var isLoginMode = true.obs;
  // 用于控制密码是否可见
  var isPasswordObscured = true.obs;
  var isConfirmPasswordObscured = true.obs;
  // API请求进行中的加载状态
  var isLoading = false.obs;
  // 用于获取输入框中的文本
  late TextEditingController emailController;
  late TextEditingController passwordController;
  late TextEditingController confirmPasswordController;
  late TextEditingController verificationCodeController;
  late TextEditingController invitationCodeController;

  Timer? _timer;
  var countdown = 60.obs;
  var isButtonEnabled = true.obs;

  @override
  void onInit() {
    super.onInit();
    emailController = TextEditingController();
    passwordController = TextEditingController();
    confirmPasswordController = TextEditingController();
    verificationCodeController = TextEditingController();
    invitationCodeController = TextEditingController();
  }

  @override
  void onClose() {
    emailController.dispose();
    passwordController.dispose();
    confirmPasswordController.dispose();
    invitationCodeController.dispose();
    _timer?.cancel();
    super.onClose();
  }

  void startTimer() {
    isButtonEnabled.value = false;
    countdown.value = 60;
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (countdown > 0) {
        countdown--;
      } else {
        timer.cancel();
        isButtonEnabled.value = true;
      }
    });
  }

  /// 切换登录/注册模式
  void toggleFormMode() {
    isLoginMode.value = !isLoginMode.value;
  }

  /// 切换密码可见性
  void togglePasswordVisibility() {
    isPasswordObscured.value = !isPasswordObscured.value;
  }

  /// 切换确认密码可见性
  void toggleConfirmPasswordVisibility() {
    isConfirmPasswordObscured.value = !isConfirmPasswordObscured.value;
  }

  /// 登录方法
  Future<void> login() async {
    if (emailController.text.isEmpty || passwordController.text.isEmpty) {
      Get.snackbar(
        '错误',
        '邮箱/手机号和密码不能为空',
        duration: Duration(seconds: 1),
      );
      return;
    }
    isLoading.value = true;
    final ApiResponse<String?> response = await _apiService.login(
      email: emailController.text,
      password: passwordController.text,
    );
    if (response.success) {
      Get.snackbar(
        '成功',
        '登录成功！',
        duration: Duration(seconds: 1),
      );
      await authController.getUserInfo();
      authController.loginFlag.value = true;
      Get.offAllNamed('/tab');
    } else {
      Get.snackbar(
        '错误',
        '登录失败: ${response.message}',
        duration: Duration(seconds: 1),
      );
    }
    isLoading.value = false;
  }

  /// 注册方法
  Future<void> register() async {
    if (emailController.text.isEmpty || passwordController.text.isEmpty || confirmPasswordController.text.isEmpty || verificationCodeController.text.isEmpty) {
      Get.snackbar('错误', '请填写所有必填项');
      return;
    }
    if (passwordController.text != confirmPasswordController.text) {
      Get.snackbar('错误', '两次输入的密码不一致');
      return;
    }
    final ApiResponse<void> response = await _apiService.register(
      email: emailController.text,
      verifyCode: verificationCodeController.text,
      password: passwordController.text,
    );
    if (response.success) {
      Get.snackbar(
        '成功',
        '注册成功！请登录。',
        duration: Duration(seconds: 1),
      );
      toggleFormMode();
    } else {
      Get.snackbar(
        '错误',
        '注册失败: ${response.message}',
        duration: Duration(seconds: 1),
      );
    }
  }

  /// 发送验证码
  Future<void> sendEmail() async {
    if (emailController.text.isEmpty || passwordController.text.isEmpty || confirmPasswordController.text.isEmpty) {
      Get.snackbar('错误', '请填写所有必填项');
      return;
    }
    if (passwordController.text != confirmPasswordController.text) {
      Get.snackbar('错误', '两次输入的密码不一致');
      return;
    }
    final ApiResponse<void> response = await _apiService.sendEmail(email: emailController.text);
    if (response.success) {
      Get.snackbar(
        '成功',
        '发送成功！',
        duration: Duration(seconds: 1),
      );
      startTimer();
    } else {
      Get.snackbar(
        '错误',
        '发送失败: ${response.message}',
        duration: Duration(seconds: 1),
      );
    }
  }
}
